package org.javaqq.face.main.conn;

import java.util.Collection;

import org.javaqq.face.main.Settings;
import org.javaqq.face.util.Utils;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.Roster.SubscriptionMode;
import org.jivesoftware.smack.packet.Presence;

public class ConnectionManger {
	private static XMPPConnection conn;
	private static Roster roster;
	private static JavaQQRosterListner rosterListner;
	private static JavaQQChatManagerListener chatManagerListener;
	
	private static final Object LOCK = new Object();
	/**
     * Login to the specified server using username, password, and workgroup.
     * Handles error representation as well as logging.
     *
     * @return true if login was successful, false otherwise
     */
    public static XMPPConnection getConnectionInstence(String server,int port,String clientInfo) {
    	synchronized (LOCK) {
    		if(conn==null){
	    		ConnectionConfiguration configureation=new ConnectionConfiguration(server, port ,clientInfo);
	    		configureation.setReconnectionAllowed(true);
	    		configureation.setRosterLoadedAtLogin(true);
	    		configureation.setSendPresence(false);
	    		conn=new XMPPConnection(configureation);
	    		chatManagerListener=new JavaQQChatManagerListener();
	    		conn.getChatManager().addChatListener(chatManagerListener);
    		}
    	}
        return conn;
    }
    
    public static XMPPConnection getConnection(){
    	if(conn==null){
    		String clientInfo=Utils.modifyWildcards(Settings.getResource());
    		conn=getConnectionInstence(Settings.getServerUrl(),Settings.getPort(),clientInfo);
    	}
    	return conn;
    }
    
    public static Roster getRoster(){
    	if(roster==null){
    		roster=getConnection().getRoster();
    		roster.setSubscriptionMode(SubscriptionMode.accept_all);
    		rosterListner=new JavaQQRosterListner();
    		roster.addRosterListener(rosterListner);
    		
    	}
    	return roster;
    }
}
